package com.example.chat.service.impl;

import com.example.chat.mapper.UserMapper;
import com.example.chat.pojo.User;
import com.example.chat.service.UserService;
import com.example.chat.utils.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    // 保存验证码的间隔时间（分钟）
    private static final long CODE_REQUEST_INTERVAL = 1;

    // 根据用户名查找用户
    @Override
    public User findByUserName(String username) {
        return userMapper.findByUserName(username);
    }

    @Override
    public void addUser(User user) {
        userMapper.add(user);
    }

    // 保存验证码到 Redis
    @Override
    public void saveVerificationCode(String email, String code) {
        redisTemplate.delete(email);
        // 使用 Redis 保存验证码并设置10分钟的过期时间
        redisTemplate.opsForValue().set(email, code, 10, TimeUnit.MINUTES);
        System.out.println("验证码已保存至Redis: " + email);
    }

    // 验证 Redis 中的验证码
    @Override
    public boolean verifyCode(String email, String code) {
        // 从 Redis 获取存储的验证码
        String storedCode = redisTemplate.opsForValue().get(email);

        // 检查验证码是否匹配
        return code.equals(storedCode);
    }

    // 根据邮箱查找用户
    @Override
    public User findByEmail(String email) {
        return userMapper.findByEmail(email);
    }

    @Override
    public void register(String username, String password) {
        User user = new User();
        user.setUsername(username);
        user.setPassword(Md5Util.getMD5String(password));
        addUser(user);
    }

    // 获取存储的验证码
    @Override
    public String getVerificationCodeByEmail(String email) {
        // 直接从 Redis 中获取验证码
        return redisTemplate.opsForValue().get(email);
    }

    // 激活用户
    @Override
    public void activateUser(String username) {
        userMapper.activateUser(username);
    }

    // 更新用户的 tokens
    @Override
    public void updateUserTokens(User user) {
        userMapper.updateUserTokens(user);
    }

}
